package org.boot.easyapi.core.dao;

import org.boot.easyapi.core.entity.ExcelConfigDO;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.jdbc.support.GeneratedKeyHolder;
import org.springframework.jdbc.support.KeyHolder;
import org.springframework.stereotype.Repository;

import javax.annotation.Resource;
import java.sql.PreparedStatement;
import java.sql.Statement;
import java.util.List;

@Repository("easyapi-excelConfigRepository")
public class ExcelConfigRepository {

    @Resource
    private JdbcTemplate jdbcTemplate;
    
    private final RowMapper<ExcelConfigDO> rowMapper = (rs, rowNum) -> {
        ExcelConfigDO fileInfo = new ExcelConfigDO();
        fileInfo.setId(rs.getLong("id"));
        fileInfo.setTableName(rs.getString("table_name"));
        fileInfo.setTag(rs.getString("tag"));
        fileInfo.setConfigKey(rs.getString("config_key"));
        fileInfo.setConfigJson(rs.getString("config_json"));
        return fileInfo;
    };

    public Long save(ExcelConfigDO excelConfigDO) {
        String sql = "INSERT INTO easyapi_core_file_info " +
                "(table_name, tag, config_key, config_json) " +
                "VALUES (?, ?, ?, ?)";
        KeyHolder keyHolder = new GeneratedKeyHolder();
        jdbcTemplate.update(connection -> {
            PreparedStatement ps = connection.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
            ps.setString(1, excelConfigDO.getTableName());
            ps.setString(2, excelConfigDO.getTag());
            ps.setString(3, excelConfigDO.getConfigKey());
            ps.setString(4, excelConfigDO.getConfigJson());
            return ps;
        }, keyHolder);
        // 返回主键 ID
        return keyHolder.getKey().longValue();
    }


    public List<ExcelConfigDO> findList(ExcelConfigDO excelConfigDO) {
        String sql = "SELECT * FROM easyapi_core_excel_config WHERE 1=1 ";
        if (excelConfigDO != null){
            if (excelConfigDO.getTableName() != null && !excelConfigDO.getTableName().isEmpty()) {
                sql += " AND table_name = '" + excelConfigDO.getTableName() + "'";
            }
            if (excelConfigDO.getTag() != null && !excelConfigDO.getTag().isEmpty()) {
                sql += " AND tag = '" + excelConfigDO.getTag() + "'";
            }
            if (excelConfigDO.getConfigKey() != null && !excelConfigDO.getConfigKey().isEmpty()) {
                sql += " AND config_key = '" + excelConfigDO.getConfigKey() + "'";
            }
        }
        return jdbcTemplate.query(sql, rowMapper);
    }

    public ExcelConfigDO findOne(Long id) {
        String sql = "SELECT * FROM easyapi_core_excel_config WHERE id = ?";
        return jdbcTemplate.queryForObject(sql, rowMapper, id);
    }
}
